package util

import (
	"time"
)

// 获取这一秒钟时间戳
func GetThisSecond() time.Time {
	return time.Now().Truncate(time.Second)
}

// 获取下一秒钟时间戳
func GetNextSecond() time.Time {
	return GetThisSecond().Add(1 * time.Second)
}

// GetThisMinute 获取这一分钟时间戳
func GetThisMinute() time.Time {
	return time.Now().Truncate(time.Minute)
}

// GetNextMinute 获取下一分钟时间戳
func GetNextMinute() time.Time {
	return GetThisMinute().Add(1 * time.Minute)
}

// GetDurationToNextMinute 获取当前和下一分钟的时差
func GetDurationToNextMinute() time.Duration {
	nextMinute := GetNextMinute()
	return nextMinute.Sub(time.Now())
}

// GetTheDayBeginTime 获取距离某时刻n天的开始时刻
func GetTheDayBeginTime(src time.Time, days int) (desc time.Time) {
	desc = time.Date(src.Year(), src.Month(), src.Day(), 0, 0, 0, 0, src.Location())
	if days != 0 {
		desc = desc.AddDate(0, 0, days)
	}
	return
}

// GetTheWeekBeginTime 获取某周周一0点0分0秒时刻
func GetTheWeekBeginTime(src time.Time) (desc time.Time) {
	todayBeginTime := time.Date(src.Year(), src.Month(), src.Day(), 0, 0, 0, 0, src.Location())
	weekday := int(todayBeginTime.Weekday())
	if weekday == 0 {
		weekday = 7
	}
	desc = todayBeginTime.AddDate(0, 0, -weekday+1)
	return
}

// GetNextHalfHour 获取整点和半小时
// 例如: 当前是19:20, 则获取到的是19:30, 如果是19:40, 获取到的是20:00
func GetNextHalfHour() time.Time {
	nowTime := time.Now()
	next := nowTime.Truncate(30 * time.Minute)
	if nowTime.After(next) {
		next = next.Add(30 * time.Minute)
	}
	return next
}

// GetDurationToNextHalfHour 获取下个整点或半小时到当前的时差
func GetDurationToNextHalfHour() time.Duration {
	return GetNextHalfHour().Sub(time.Now())
}

const DefaultTimeFormat = "2006-01-02 15:04:05"

// ParseTimeStringByFormat 解析时间字符串, 返回UTC时间
func ParseTimeStringByFormat(fmt string, strTime string) (time.Time, error) {
	t, err := time.Parse(fmt, strTime)
	return t, err
}
func ParseTimeString(strTime string) (time.Time, error) {
	t, err := time.Parse(DefaultTimeFormat, strTime)
	return t, err
}

// ParseTimeStringInLocationByFormat 解析时间字符串, 返回本地时间
func ParseTimeStringInLocationByFormat(fmt string, strTime string) (time.Time, error) {
	t, err := time.ParseInLocation(fmt, strTime, time.Local)
	return t, err
}

func ParseTimeStringInLocation(strTime string) (time.Time, error) {
	t, err := time.ParseInLocation(DefaultTimeFormat, strTime, time.Local)
	return t, err
}

// IsSameDayUnixTimeStamp 判断2个unix时间戳是不是同一天
func IsSameDayUnixTimeStamp(t1 int64, t2 int64) bool {
	t1DayBeginTime := GetTheDayBeginTime(time.Unix(t1, 0), 0)
	t2DayBeginTime := GetTheDayBeginTime(time.Unix(t2, 0), 0)
	return t1DayBeginTime.Equal(t2DayBeginTime)
}

func IsSameDay(t1 time.Time, t2 time.Time) bool {
	return t1.Year() == t2.Year() && t1.YearDay() == t2.YearDay()
}
